package com.nuanshui.heatedloan.credit.rabbitmq;

import com.nuanshui.framework.lang.DateUtil;
import com.nuanshui.framework.springContext.SpringPropertiesUtil;
import com.nuanshui.framework.utils.LogUtil;
import com.nuanshui.heatedloan.constant.RabbitMqQueue;
import com.nuanshui.heatedloan.credit.constant.BorrowType;
import com.nuanshui.heatedloan.credit.constant.CalculateLateFeeRequest;
import com.nuanshui.heatedloan.credit.constant.OrderType;
import com.nuanshui.heatedloan.credit.facade.CustomerProduceService;
import com.nuanshui.heatedloan.credit.facade.PayOrderInfoService;
import com.nuanshui.heatedloan.credit.facade.job.PayOrderJobService;
import com.nuanshui.heatedloan.credit.model.LightLoanProductInfo;
import com.nuanshui.heatedloan.credit.model.SingleLoanProductInfo;
import com.nuanshui.heatedloan.credit.request.OrderJobParams;
import com.nuanshui.heatedloan.credit.utils.CalculateLoanAmt;
import com.nuanshui.heatedloan.credit.vo.PayOrderInfoVO;
import com.nuanshui.heatedloan.middleware.rabbitmq.RabbitmqMessageHandler;
import com.nuanshui.heatedloan.middleware.rabbitmq.annotation.MqMessageHandler;
import com.nuanshui.heatedloan.task.facade.constant.TaskEnum;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

/**
 * Created by wangxw on 2017/7/25.
 * 逾期费计算消息队列
 * 生成下一个定时计算逾期的定时任务，
 * 次数不定，最大的次数不定
 * 每天的凌晨00分开始执行
 */

@MqMessageHandler(RabbitMqQueue.RABBIT_MQ_CALCULATE_LATE_PAYMENT_JOB)
public class DealCalculateLatepaymentHandler implements RabbitmqMessageHandler {

    private static Logger logger = LoggerFactory.getLogger("DealCalculateLatepaymentHandler");

    @Autowired
    private PayOrderInfoService payOrderInfoService;

    @Autowired
    private PayOrderJobService payOrderJobService;

    @Autowired
    private CustomerProduceService customerProduceService;

    public void onMessage(Message message, Channel channel ) throws Exception{
        try{
            int hour=Integer.parseInt(SpringPropertiesUtil.getPropertiestValue("credit.reminder.hour"));
            LogUtil.info(logger, "------开始提醒的时间为"+hour+"------");
            byte[] body = message.getBody();
            String orderNum = new String(body);
            if (orderNum.endsWith("\"")) {
                orderNum = orderNum.substring(1, orderNum.length() - 1);
            }
            LogUtil.info(logger, String.format("---------------------orderNum : %s-----------", orderNum));
            PayOrderInfoVO payOrderInfoVO=payOrderInfoService.loadVOByOrderNo(orderNum);
            int loanAmt=payOrderInfoVO.getLoanAmount();
            long intervalDay=DateUtil.getIntervalDay(new Date(),payOrderInfoVO.getShouldReturnTime());  //计算逾期天数
            int day=(int)intervalDay;
            int lateFee=this.updateLateFee(payOrderInfoVO,day);
            //启动下一个定时任务
            this.createNextQuartz(payOrderInfoVO,day,lateFee);
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }
    }
    private int updateLateFee(PayOrderInfoVO payOrderInfoVO,int day){
        LogUtil.info(logger, "-------------开始计算逾期费-----------");
        int lateFee;
        int orderAmt=payOrderInfoVO.getOrderAmount();  //总费用
        int loanAmt=payOrderInfoVO.getLoanAmount();
        CalculateLateFeeRequest calculateLateFeeRequest=new CalculateLateFeeRequest();
        calculateLateFeeRequest.setBorrowType(payOrderInfoVO.getBorrowType());
        calculateLateFeeRequest.setLateDay(day);   //逾期天数
        calculateLateFeeRequest.setLoanAmt(payOrderInfoVO.getLoanAmount());
        calculateLateFeeRequest.setPayAmt(0);
        if(BorrowType.SINGLELOAN ==payOrderInfoVO.getBorrowType()){
            SingleLoanProductInfo singleLoanProductInfo =customerProduceService.
                    getSingleLoanProductInfo();
            calculateLateFeeRequest.setSingleFeeRateSmall(singleLoanProductInfo.getLateFeeBefore());
            LogUtil.info(logger, String.format("---------------------LateFeeBefore:%s-----------", singleLoanProductInfo.getLateFeeBefore()));
            calculateLateFeeRequest.setSingleFeeRateBig(singleLoanProductInfo.getLateFeeAfter());
            calculateLateFeeRequest.setBeginDay(singleLoanProductInfo.getBeforeDay());
            LogUtil.info(logger, String.format("---------------------LateFeeAfter:%s-----------", singleLoanProductInfo.getLateFeeAfter()));
        }else if(BorrowType.LIGHTLOAN==payOrderInfoVO.getBorrowType()){
            LightLoanProductInfo lightLoanProductInfo=customerProduceService.
                    getLightLoanProductInfo();
            calculateLateFeeRequest.setLightFeeRate(lightLoanProductInfo.getLateFee());
            LogUtil.info(logger, String.format("---------------------LateFee:%s-----------", lightLoanProductInfo.getLateFee()));
            calculateLateFeeRequest.setBeginDay(lightLoanProductInfo.getBeforeDay());
        }
        int lateFeeCal= CalculateLoanAmt.calculateLateFee(calculateLateFeeRequest);  //逾期费用
        lateFee=(orderAmt+lateFeeCal)>2*loanAmt?(2*loanAmt-orderAmt):lateFeeCal;
        LogUtil.info(logger, "-------------开始更新逾期数据-----------");
        payOrderInfoService.updateLateInfoByOrderNo(payOrderInfoVO.getOrderNo(),lateFee,day, OrderType.OVERDUEPAYMENT);
        LogUtil.info(logger, "-------------更新逾期数据完成-----------");
        return lateFeeCal;
    }

    private void createNextQuartz(PayOrderInfoVO payOrderInfoVO,int day,int lateFee) {
        if (day < 120 && (payOrderInfoVO.getOrderAmount() + lateFee) <= 2 * payOrderInfoVO.getLoanAmount()) {
            LogUtil.info(logger, "-------------开始启动逾期计费下一个任务-----------");
            Date lateCostDate = DateUtil.getDateHourMinuteSecond(new Date(), 0, 0, 0);
            Date lateNextCostDateDateUtil = DateUtil.addDays(lateCostDate, 1);
            OrderJobParams lateFreeCalJobParams = new OrderJobParams();
            lateFreeCalJobParams.setOrderNo(payOrderInfoVO.getOrderNo());
            lateFreeCalJobParams.setOrderExpireTime(lateNextCostDateDateUtil);
            lateFreeCalJobParams.setTaskType(TaskEnum.CALCULATE_LATE_PAYMENT_JOB);
            payOrderJobService.createExpireRefundJob(lateFreeCalJobParams);
            LogUtil.info(logger, "-------------启动逾期计费下一个任务完成-----------");
            LogUtil.info(logger, "-------------计算逾期费完成-----------");
        }
    }
}
